package com.oocl.servlet;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.oocl.exception.MyException;
import com.oocl.pojo.Book;
import com.oocl.service.BookService;
import com.oocl.service.impl.BookServiceFactory;
import com.oocl.service.impl.ServiceFactory;




public class AddPurchaseServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String bId = request.getParameter("bId");
		Map<String, Integer> cart = (Map<String, Integer>) request.getSession()
				.getAttribute("cart");
		if (cart == null) {
			cart = new HashMap<String, Integer>();
		}
		Integer count = cart.get(bId);
		if (count == null) {
			count = 1;
		} else {
			count++;
		}
		cart.put(bId, count);
		request.getSession().setAttribute("cart", cart);

		Set<String> set = cart.keySet();
		try {
			BookServiceFactory factory = (BookServiceFactory) ServiceFactory
					.getServiceFactory(BookServiceFactory.BOOK);
			BookService pSer = factory.getService();
			List<Book> list = new ArrayList<Book>();
			for (String id : set) {
				Book book = pSer.loadBook(id);
				book.setNum(cart.get(id));
				list.add(book);
			}
			request.setAttribute("list", list);
			request.getRequestDispatcher("cart.jsp").forward(request, response);
		} catch (MyException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException {
		doGet(request,response);
	}

}
